package com.norriekoelle.virtualsensors.kinect;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;

/**
 * Note: Storage permission set in manifest
 * 
 * @author norrielm
 *
 */
public class LogToFile {

	public String name;
	private FileOutputStream fo = null;
	private String path;
	
	/**Initialise with chosen filename*/
	public LogToFile(String filename){
		name = filename;
		create();
	}
	
	/**Create the file to write in to, save on the phone's sdcard*/
	public void create(){
		try {			
			path = Environment.getExternalStorageDirectory().getAbsolutePath() 
				+ "/"+ name +".txt";
			Log.d("logfile", "path: " + path);
			
			String state = android.os.Environment.getExternalStorageState();
			if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
				Log.d("logfile" , "could not mount sdcard");
			}

			// make sure the directory we plan to store the recording in exists
			File directory = new File(path).getParentFile();
			if (!directory.exists() && !directory.mkdirs()) {
				Log.d("logfile" , "log dir not found");			
			}
			
			File file = new File(path);
			fo=new FileOutputStream(file, true);

			
		} catch (FileNotFoundException e) {
			Log.d("logfile" , "Could not open log file " + e);
		}catch(Exception e){
			Log.d("logfile" , "Could not open log file " + e);
		}
	}
	
	/**Write a string*/
	public void write(String s){
		if(fo!= null){
			try {
				s+="\n";
				fo.write(s.getBytes());
			} catch (IOException e) {
				Log.d("logfile" , "could not write to log " + e);
			}
		}else{
			Log.d("logfile" , "fo == null");
		}
	}

	/**Write a string with the time beside it [hh:mm]*/
	public void writeWTime(String s){
		if(fo!= null){
			try {
				//String time = "(" + DateFormat.format("hh:mm:ss", new Date()) + ")"; 
				//time += s+"\n";
				String time = System.currentTimeMillis() + " " + s +"\n";
				fo.write(time.getBytes());
			} catch (IOException e) {
				Log.d("logfile" , "could not write to log w/time " + e);
			}
		}else{
			Log.d("logfile" , "fo == null");
		}
	}	
	
	/**Returns the path to the log*/
	public String getFilename(){
		return path;
	}
	
	/**Close the log file*/
	public void close(){
		if(fo!=null){
			try {
				fo.close();
			} catch (IOException e) {
				Log.d("logfile" , "could not close fo " + e);				
			}
		}
	}
	
}